﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataLayer.Entities;
using DataLayer.Interfaces;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.SqlCommand;

namespace DataLayer.Implementations
{
    public class UserApplication : GeneralApplication<User>
    {   
        public User GetByUsernameAndPassword(User user)
        {
            List<ICriterion> conditions = new List<ICriterion>();
            conditions.Add(Restrictions.Eq("Username", user.Username));
            conditions.Add(Restrictions.Eq("Password", user.Password));
            
            return model.GetByCriterion<User>(conditions).FirstOrDefault();
        }

        public IList<User> GetRandomDonutsUsers(bool random)
        {
            List<ICriterion> conditions = new List<ICriterion>();
            conditions.Add(Restrictions.Eq("PrefersRandom", random));

            return model.GetByCriterion<User>(conditions);
        }

        public IList<User> GetUsersByRoleId(int roleId)
        {
            List<ICriterion> conditions = new List<ICriterion>();
            conditions.Add(Restrictions.Eq("Role.RoleId", roleId));

            return model.GetByCriterion<User>(conditions);
        }

        public Role GetRoleById(int id)
        {
            return model.GetById<Role>(id);
        }
        
        public User GetByEmail(string email)
        {
            List<ICriterion> conditions = new List<ICriterion>();
            conditions.Add(Restrictions.Eq("Email", email));

            return model.GetByCriterion<User>(conditions).FirstOrDefault();
        }

        public IList<User> GetAllByEmail(string email)
        {
            List<ICriterion> conditions = new List<ICriterion>();
            conditions.Add(Restrictions.Eq("Email", email));

            return model.GetByCriterion<User>(conditions);
        }

        public User GetByUsername(string username)
        {
            List<ICriterion> conditions = new List<ICriterion>();
            conditions.Add(Restrictions.Eq("Username", username));

            return model.GetByCriterion<User>(conditions).FirstOrDefault();
        }

        public IList<User> GetUsersToActivate()
        {
            List<ICriterion> conditions = new List<ICriterion>();
            conditions.Add(Restrictions.Eq("IsActive", true));
            conditions.Add(Restrictions.Gt("CreatedDate", DateTime.Today.AddMonths(-1)));
            
            return model.GetByCriterion<User>(conditions);
        }

        public void Save(User user)
        {
            user.ModifiedDate = DateTime.Now;
            if (user.UserId == null)
            {
                Save(user, 0);
            }else{
                Save(user, user.UserId.Value);
            }
        }
    }
}
